#include <dbg.h>

#include <cassert>
using namespace std;

class Solution {
public:
    long long maxSum(vector<int>& nums, int m, int k) {
        long long sum = 0;
        long long res = 0;
        unordered_map<int, int> cnt;
        for (int i = 0; i < nums.size(); ++i) {
            sum += nums[i];  // 更新
            ++cnt[nums[i]];

            if (i < k - 1) {  // 不够k个
                continue;
            }

            if (cnt.size() >= m) {  // 满足条件
                res = max(sum, res);
            }

            sum -= nums[i - k + 1];  // 移动窗口
            if (--cnt[nums[i - k + 1]] == 0) {
                cnt.erase(nums[i - k + 1]);
            }
        }
        return res;
    }
};

int main() {
    Solution s;
    vector<int> nums1 = {2, 6, 7, 3, 1, 7};
    int m1 = 3;
    int k1 = 4;
    long long res1 = 18;
    vector<int> nums2 = {5, 9, 9, 2, 4, 5, 4};
    int m2 = 1;
    int k2 = 3;
    long long res2 = 23;
    vector<int> nums3 = {1, 2, 1, 2, 1, 2, 1};
    int m3 = 3;
    int k3 = 3;
    long long res3 = 0;
    assert(s.maxSum(nums1, m1, k1) == res1);
    assert(s.maxSum(nums2, m2, k2) == res2);
    assert(s.maxSum(nums3, m3, k3) == res3);
}